﻿
namespace Sissonix.ExtRest
{

    static class StringExtensions
    {
        public const string PATHDELIM = @"/";
        public const string WRONGDELIM = @"\";

        public static string WADLIdentifier(this string s)
        {
            if (s.IsWADLIdentifier())
            {
                return s.Trim().Substring(1, s.Length - 2);
            }
            else
                return "";
        }

        public static bool IsWADLIdentifier(this string s)
        {
            return s.StartsWith("{") && s.EndsWith("}");
        }

        public static int OccuranceCount(this string s, string pattern)
        {
            int count = 0;
            int i = 0;
            while ((i = s.IndexOf(pattern, i)) != -1)
            {
                i += pattern.Length;
                count++;
            }
            return count;
        }

        public static string StripStartsWith(this string s, string stripString)
        {
            if (s.StartsWith(stripString))
                return s.Remove(0, stripString.Length);
            else
                return s;
        }
        
        public static string FixPath(this string s)
        {
            return s.FixDelims().StripLastDelims();
        }

        public static string StripLastDelims(this string s)
        {
            string rslt = s;
            while (rslt.EndsWith(PATHDELIM) || rslt.EndsWith(WRONGDELIM))
                rslt = rslt.Remove(rslt.Length-1);

            return rslt;
        }
        
        public static string StripFirstDelims(this string s)
        {
            string rslt = s;
            while (rslt.StartsWith(PATHDELIM) || rslt.StartsWith(WRONGDELIM))
                rslt = rslt.Remove(0,1);

            return rslt;
        }

        public static string StripFirstLastDelims(this string s)
        {
            return s.StripFirstDelims().StripLastDelims();
        }

        public static string FixDelims(this string s)
        {
            return s.Replace(WRONGDELIM, PATHDELIM);
        }

    }
}
